<template>
  <div class="profile-page">
    <div class="page-content">
      <!-- 个人信息卡片 -->
      <div class="profile-card">
        <div class="profile-header">
          <div class="avatar-section">
            <el-avatar :size="120" :src="userProfile?.avatar">
              {{ userProfile?.nickname?.charAt(0) || userProfile?.username?.charAt(0) }}
            </el-avatar>
            <div class="upload-overlay" @click="uploadAvatar">
              <el-icon><Camera /></el-icon>
              <span>更换头像</span>
            </div>
          </div>

          <div class="profile-info">
            <h2 class="username">{{ userProfile?.username }}</h2>
            <p class="nickname">{{ userProfile?.nickname || "未设置昵称" }}</p>
            <p class="bio">{{ userProfile?.profile?.bio || "这个人很懒，什么都没有留下..." }}</p>

            <div class="profile-stats">
              <div class="stat-item">
                <span class="stat-value">{{ stats.postCount }}</span>
                <span class="stat-label">帖子</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ stats.followerCount }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ stats.followingCount }}</span>
                <span class="stat-label">关注</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ stats.whisperCount }}</span>
                <span class="stat-label">悄悄话</span>
              </div>
            </div>
          </div>
        </div>

        <div class="profile-actions">
          <el-button type="primary" @click="showEditDialog = true">
            <el-icon><Edit /></el-icon>
            编辑资料
          </el-button>
          <el-button @click="$router.push('/whisper')">
            <el-icon><ChatDotRound /></el-icon>
            发悄悄话
          </el-button>
        </div>
      </div>

      <!-- 内容切换标签 -->
      <div class="content-tabs-card">
        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane label="个人信息" name="info">
            <div class="detail-info">
              <div class="info-grid">
                <div class="info-item">
                  <label>邮箱：</label>
                  <span>{{ userProfile?.email }}</span>
                </div>
                <div class="info-item">
                  <label>性别：</label>
                  <span>{{ getGenderText(userProfile?.profile?.gender) }}</span>
                </div>
                <div class="info-item">
                  <label>手机：</label>
                  <span>{{ userProfile?.profile?.phone || "未设置" }}</span>
                </div>
                <div class="info-item">
                  <label>生日：</label>
                  <span>{{ userProfile?.profile?.birthday || "未设置" }}</span>
                </div>

                <div class="info-item">
                  <label>加入时间：</label>
                  <span>{{ formatTime(userProfile?.createdAt) }}</span>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="我的帖子" name="posts">
            <div class="my-posts" v-loading="postsLoading">
              <div class="posts-header">
                <h4>我的帖子</h4>
                <el-button type="primary" @click="$router.push('/posts/create')">
                  <el-icon><Plus /></el-icon>
                  发布新帖
                </el-button>
              </div>

              <div v-if="myPosts.length === 0 && !postsLoading" class="empty-state">
                <el-empty description="暂无发布的帖子">
                  <template #image>
                    <el-icon style="font-size: 80px; color: #ddd"><Document /></el-icon>
                  </template>
                  <el-button type="primary" @click="$router.push('/posts/create')">
                    立即发布
                  </el-button>
                </el-empty>
              </div>

              <div v-else class="posts-list">
                <div class="post-item" v-for="post in myPosts" :key="post.id">
                  <h5 class="post-title" @click="$router.push(`/posts/${post.id}`)">
                    {{ post.title }}
                  </h5>
                  <p class="post-summary">{{ post.summary }}</p>
                  <div class="post-meta">
                    <span class="post-date">{{ formatTime(post.createdAt) }}</span>
                    <div class="post-stats">
                      <span
                        ><el-icon><View /></el-icon> {{ post.viewCount }}</span
                      >
                      <span
                        ><el-icon><ChatDotSquare /></el-icon> {{ post.commentCount }}</span
                      >
                      <span
                        ><el-icon><Star /></el-icon> {{ post.likeCount }}</span
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="我的悄悄话" name="whispers">
            <div class="my-whispers" v-loading="whispersLoading">
              <div class="whispers-header">
                <h4>收到的悄悄话</h4>
                <el-button type="primary" @click="$router.push('/whisper')">
                  <el-icon><ChatDotRound /></el-icon>
                  发悄悄话
                </el-button>
              </div>

              <div v-if="myWhispers.length === 0 && !whispersLoading" class="empty-state">
                <el-empty description="暂无悄悄话">
                  <template #image>
                    <el-icon style="font-size: 80px; color: #ddd"><ChatDotRound /></el-icon>
                  </template>
                  <el-button type="primary" @click="$router.push('/whisper')"> 去悄悄话 </el-button>
                </el-empty>
              </div>

              <div v-else class="whispers-list">
                <div class="whisper-item" v-for="whisper in myWhispers" :key="whisper.id">
                  <div class="whisper-content">
                    <p>{{ whisper.content }}</p>
                  </div>
                  <div class="whisper-meta">
                    <span class="whisper-from"> 来自：{{ whisper.senderName || "匿名用户" }} </span>
                    <span class="whisper-time">{{ formatTime(whisper.createdAt) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑个人资料"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="editForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            maxlength="100"
            show-word-limit
          />
          <div class="form-tip">
            <el-text type="warning" size="small">
              <el-icon><Warning /></el-icon>
              修改邮箱后需要重新进行邮箱验证
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="editForm.bio"
            type="textarea"
            :rows="3"
            placeholder="介绍一下自己..."
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="0">保密</el-radio>
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="updateProfile" :loading="updating"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import {
  Camera,
  Edit,
  ChatDotRound,
  Plus,
  Document,
  View,
  Star,
  ChatDotSquare,
  Warning,
} from "@element-plus/icons-vue";
import { useStore } from "vuex";
import type { UserDTO } from "@/api/user";
import { getPostsByAuthor, deletePost as deletePostApi, type PostDTO } from "@/api/posts";
import { getSentWhispers, type WhisperDTO } from "@/api/whisper";
import {
  getUserStats,
  updateUserProfile,
  getCurrentUser,
  type UserStats,
  type UserUpdateRequest,
} from "@/api/user";

const store = useStore();

// 响应式数据
const loading = ref(false);
const updating = ref(false);
const showEditDialog = ref(false);
const editFormRef = ref<FormInstance>();
const activeTab = ref("info");

// 帖子相关数据
const postsLoading = ref(false);
const myPosts = ref<PostDTO[]>([]);
const postsPage = ref(1);
const postsSize = ref(10);
const postsTotal = ref(0);

// 悄悄话相关数据
const whispersLoading = ref(false);
const myWhispers = ref<WhisperDTO[]>([]);
const whispersPage = ref(1);
const whispersSize = ref(10);
const whispersTotal = ref(0);

const userProfile = ref<UserDTO | null>(null);
const stats = reactive<UserStats>({
  postCount: 0,
  followerCount: 0,
  followingCount: 0,
  whisperCount: 0,
  commentCount: 0,
  likeCount: 0,
});

// 编辑表单
const editForm = reactive({
  email: "",
  nickname: "",
  bio: "",
  gender: "0",
  phone: "",
  birthday: "",
});

// 表单验证规则
const editRules = {
  email: [
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
    { max: 100, message: "邮箱长度不能超过100个字符", trigger: "blur" },
  ],
  nickname: [{ max: 50, message: "昵称长度不能超过50个字符", trigger: "blur" }],
  bio: [{ max: 200, message: "个人简介长度不能超过200个字符", trigger: "blur" }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }],
};

// 加载用户资料
const loadProfile = async () => {
  loading.value = true;
  try {
    // 从后端API获取当前用户最新信息
    const currentUser = await getCurrentUser();
    userProfile.value = currentUser;

    // 填充编辑表单
    editForm.email = currentUser.email || "";
    editForm.nickname = currentUser.nickname || "";
    editForm.bio = currentUser.profile?.bio || "";
    editForm.gender = currentUser.profile?.gender || "0";
    editForm.phone = currentUser.profile?.phone || "";
    editForm.birthday = currentUser.profile?.birthday || "";

    // 加载用户数据
    await Promise.all([loadUserStats(), loadMyPosts(), loadMyWhispers()]);
  } catch (error) {
    console.error("Failed to load profile:", error);
    ElMessage.error("加载用户资料失败");
  } finally {
    loading.value = false;
  }
};

// 加载用户统计数据
const loadUserStats = async () => {
  if (!userProfile.value) return;

  try {
    const userStats = await getUserStats(userProfile.value.id);
    Object.assign(stats, userStats);
  } catch (error) {
    console.error("Failed to load user stats:", error);
    // 使用默认值，不显示错误
  }
};

// 加载我的帖子
const loadMyPosts = async () => {
  if (!userProfile.value) return;

  postsLoading.value = true;
  try {
    const response = await getPostsByAuthor(userProfile.value.id, postsPage.value, postsSize.value);

    myPosts.value = response.items || [];
    postsTotal.value = response.total || 0;
  } catch (error) {
    console.error("Failed to load my posts:", error);
    ElMessage.error("加载我的帖子失败");
  } finally {
    postsLoading.value = false;
  }
};

// 加载我的悄悄话
const loadMyWhispers = async () => {
  if (!userProfile.value) return;

  whispersLoading.value = true;
  try {
    const response = await getSentWhispers(whispersPage.value, whispersSize.value);

    myWhispers.value = response.items || [];
    whispersTotal.value = response.total || 0;
  } catch (error) {
    console.error("Failed to load my whispers:", error);
    ElMessage.error("加载我的悄悄话失败");
  } finally {
    whispersLoading.value = false;
  }
};

// 帖子分页
const handlePostsPageChange = (page: number) => {
  postsPage.value = page;
  loadMyPosts();
};

// 悄悄话分页
const handleWhispersPageChange = (page: number) => {
  whispersPage.value = page;
  loadMyWhispers();
};

// 删除帖子
const deletePost = async (postId: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这篇帖子吗？", "确认删除", {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning",
    });

    await deletePostApi(postId);
    ElMessage.success("删除成功");
    loadMyPosts();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

// 更新资料
const updateProfile = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();

    updating.value = true;

    // 调用API更新用户资料
    const updateData: UserUpdateRequest = {
      email: editForm.email,
      nickname: editForm.nickname,
      bio: editForm.bio,
      gender: editForm.gender,
      phone: editForm.phone,
      birthday: editForm.birthday,
    };

    await updateUserProfile(updateData);

    // 更新本地数据
    if (userProfile.value) {
      userProfile.value.email = editForm.email;
      userProfile.value.nickname = editForm.nickname;
      if (userProfile.value.profile) {
        userProfile.value.profile.bio = editForm.bio;
        userProfile.value.profile.gender = editForm.gender;
        userProfile.value.profile.phone = editForm.phone;
        userProfile.value.profile.birthday = editForm.birthday;
      }
    }

    // 更新store中的用户信息（只更新profile相关字段）
    store.dispatch("auth/updateUser", {
      nickname: editForm.nickname,
      profile: {
        bio: editForm.bio,
        gender: editForm.gender,
        phone: editForm.phone,
        birthday: editForm.birthday,
      },
    });

    showEditDialog.value = false;
    ElMessage.success("资料更新成功");
  } catch (error: any) {
    console.error("Update profile error:", error);
    ElMessage.error(error.message || "更新失败");
  } finally {
    updating.value = false;
  }
};

// 上传头像
const uploadAvatar = () => {
  ElMessage.info("头像上传功能开发中...");
};

// 获取性别文本
const getGenderText = (gender?: string) => {
  switch (gender) {
    case "1":
      return "男";
    case "2":
      return "女";
    default:
      return "保密";
  }
};

// 格式化时间
const formatTime = (time?: string) => {
  if (!time) return "未知";
  const date = new Date(time);
  return date.toLocaleDateString();
};

// 组件挂载
onMounted(() => {
  loadProfile();
});
</script>

<style scoped lang="scss">
.profile-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px 0;

  .page-content {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 20px;

    .profile-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      padding: 32px;
      margin-bottom: 24px;

      .profile-header {
        display: flex;
        gap: 24px;
        margin-bottom: 24px;

        .avatar-section {
          position: relative;
          flex-shrink: 0;

          .upload-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: white;
            opacity: 0;
            transition: opacity 0.3s;
            cursor: pointer;

            &:hover {
              opacity: 1;
            }

            span {
              font-size: 12px;
              margin-top: 4px;
            }
          }
        }

        .profile-info {
          flex: 1;

          .username {
            margin: 0 0 8px 0;
            color: #2c3e50;
            font-size: 24px;
            font-weight: 600;
          }

          .nickname {
            margin: 0 0 12px 0;
            color: #606266;
            font-size: 16px;
          }

          .bio {
            margin: 0 0 20px 0;
            color: #909399;
            line-height: 1.6;
          }

          .profile-stats {
            display: flex;
            gap: 32px;

            .stat-item {
              display: flex;
              flex-direction: column;
              align-items: center;

              .stat-value {
                font-size: 20px;
                font-weight: 600;
                color: #2c3e50;
              }

              .stat-label {
                font-size: 14px;
                color: #909399;
                margin-top: 4px;
              }
            }
          }
        }
      }

      .profile-actions {
        display: flex;
        gap: 12px;
        justify-content: center;
      }
    }

    .content-tabs-card {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      padding: 24px;

      .detail-info {
        .info-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
          gap: 16px;

          .info-item {
            display: flex;
            align-items: center;

            label {
              color: #909399;
              font-size: 14px;
              min-width: 80px;
            }

            span {
              color: #2c3e50;
              font-size: 14px;
            }
          }
        }
      }

      .my-posts,
      .my-whispers {
        .posts-header,
        .whispers-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;

          h4 {
            margin: 0;
            color: #2c3e50;
            font-size: 18px;
            font-weight: 600;
          }
        }

        .empty-state {
          text-align: center;
          padding: 40px 0;
          color: #909399;
        }

        .posts-list,
        .whispers-list {
          .post-item,
          .whisper-item {
            border: 1px solid #ebeef5;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            transition: all 0.3s;

            &:hover {
              border-color: #c6e2ff;
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            .post-header,
            .whisper-header {
              display: flex;
              justify-content: space-between;
              align-items: flex-start;
              margin-bottom: 12px;

              .post-info {
                flex: 1;
                margin-right: 16px;

                .post-title {
                  margin: 0 0 8px 0;
                  color: #2c3e50;
                  font-size: 16px;
                  font-weight: 600;
                  cursor: pointer;
                  transition: color 0.3s;

                  &:hover {
                    color: #409eff;
                  }
                }

                .post-summary {
                  margin: 0;
                  color: #606266;
                  font-size: 14px;
                  line-height: 1.6;
                }
              }

              .receiver-info {
                .receiver-name {
                  font-weight: 500;
                  color: #2c3e50;
                  margin-right: 16px;
                }

                .send-time {
                  font-size: 12px;
                  color: #909399;
                }
              }

              .post-actions {
                display: flex;
                gap: 8px;
                flex-shrink: 0;
              }
            }

            .post-content,
            .whisper-content {
              color: #606266;
              line-height: 1.6;
              margin-bottom: 12px;
            }

            .whisper-content {
              background: #f8f9fa;
              padding: 12px;
              border-radius: 6px;
            }

            .post-meta,
            .whisper-meta {
              display: flex;
              justify-content: space-between;
              align-items: center;

              .meta-left {
                display: flex;
                align-items: center;
                gap: 12px;

                .post-date {
                  color: #909399;
                  font-size: 12px;
                }
              }

              .meta-right {
                display: flex;
                align-items: center;
                gap: 16px;

                .meta-stat {
                  display: flex;
                  align-items: center;
                  gap: 4px;
                  color: #909399;
                  font-size: 12px;
                }
              }
            }

            .whisper-meta {
              justify-content: flex-end;
              gap: 8px;
            }
          }
        }

        .pagination {
          display: flex;
          justify-content: center;
          margin-top: 24px;
        }
      }
    }
  }
}

// 表单提示样式
.form-tip {
  margin-top: 4px;

  .el-text {
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .profile-page {
    .page-content {
      padding: 0 10px;

      .profile-card {
        padding: 20px;

        .profile-header {
          flex-direction: column;
          align-items: center;
          text-align: center;

          .profile-info .profile-stats {
            justify-content: center;
          }
        }
      }

      .content-tabs-card {
        padding: 16px;

        .detail-info .info-grid {
          grid-template-columns: 1fr;
        }

        .my-posts,
        .my-whispers {
          .posts-list,
          .whispers-list {
            .post-item,
            .whisper-item {
              .post-header,
              .whisper-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;

                .post-actions {
                  align-self: flex-end;
                }
              }

              .post-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
              }

              .whisper-meta {
                justify-content: flex-start;
              }
            }
          }
        }
      }
    }
  }
}
</style>
